package com.umpay.sp.saas.util;


import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.umpay.operation.common.ReqMessage;
import com.umpay.operation.common.ResMessage;
import com.umpay.operation.model.spapplyplat.AppChannel;
import com.umpay.operation.service.applet.StoreInfServiceRemote;
import com.umpay.operation.service.fundPurchase.FundServiceRemote;
import com.umpay.operation.service.saas.TStoreBatchDetailServiceRemote;
import com.umpay.operation.service.saas.TStoreBatchServiceRemote;
import com.umpay.operation.service.spapplyplat.remote.AppChannelServiceRemote;
import com.umpay.sp.common.LoggerManager;
import com.umpay.sp.web.util.PropertyUtil;

/**
 * 数据入表工具类
 * ================================================================================
 * 		保存批次信息
 * 		更新批次信息
 * 		保存批次详情信息
 * 		更新批次详情信息
 * 		创建店铺信息
 * ================================================================================
 * @author ChenFuLong
 *
 */
public class DataEntryUtil {

	public final static Logger logger = LoggerManager.getBusiLogger();
	
	public static final AppChannelServiceRemote appChannelServiceRemote = DubboInvokerUtil.getInvoker(AppChannelServiceRemote.class);
	public static final FundServiceRemote fundServiceRemote = DubboInvokerUtil.getInvoker(FundServiceRemote.class);
	public final static StoreInfServiceRemote storeInfServiceRemote = DubboInvokerUtil.getInvoker(StoreInfServiceRemote.class);
	public final static TStoreBatchServiceRemote tStoreBatchServiceRemote = DubboInvokerUtil.getInvoker(TStoreBatchServiceRemote.class);
	public final static TStoreBatchDetailServiceRemote tStoreBatchDetailServiceRemote = DubboInvokerUtil.getInvoker(TStoreBatchDetailServiceRemote.class);
	
	public static final String PRODUCTID_ADVANCESETTLE = PropertyUtil.getStrValue("spEnterpriseWeb_config.properties","productId_advanceSettle", "");
	public static final String FUND_OPEN_ACCSEARCH = PropertyUtil.getStrValue("spEnterpriseWeb_config.properties","fundOpenAccSearch", "");
	public static final String SAAS_FUNDNO = PropertyUtil.getStrValue("spEnterpriseWeb_config.properties","saas.fundNo", "");
	public static final String SAAS_FUNDMERID = PropertyUtil.getStrValue("spEnterpriseWeb_config.properties","saas.fundMerId", "");
	public static final String B_PRODUCT_ID = PropertyUtil.getStrValue("spEnterpriseWeb_config.properties","bProductId", "");
	
	/**
	 * 根据主键查询批量批次信息
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public static ResMessage getStoreBatchByPri(ReqMessage req) throws Exception{
		logger.info("【根据主键查询批量批次信息】开始");
		logger.info("【根据主键查询批量批次信息】入参" + req);
		ResMessage res = tStoreBatchServiceRemote.getStoreBatchByPri(req);
		logger.info("【根据主键查询批量批次信息】出参" + res);
		return res;
	}
	
	/**
	 * 保存批次信息
	 * @param req
	 * @return
	 * @throws Exception 
	 */
	public static ResMessage saveBatch(ReqMessage req) throws Exception{
		logger.info("【保存批次信息】开始");
		logger.info("【保存批次信息】入参" + req);
		ResMessage res = tStoreBatchServiceRemote.insetStoreBatch(req);
		logger.info("【保存批次信息】出参" + res);
		return res;
	}
	
	/**
	 * 更新批次信息
	 * @param req
	 * @return
	 * @throws Exception 
	 */
	public static ResMessage updateBatch(ReqMessage req) throws Exception{
		logger.info("【更新批次信息】开始");
		logger.info("【更新批次信息】入参" + req);
		ResMessage res = tStoreBatchServiceRemote.updateStoreBatchByPri(req);
		logger.info("【更新批次信息】出参" + res);
		return res;
	}
	
	/**
	 * 根据主键查询批次详情信息
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public static ResMessage getBatchDetailByPri(ReqMessage req) throws Exception{
		logger.info("【根据主键查询批次详情信息】开始");
		logger.info("【根据主键查询批次详情信息】入参" + req);
		ResMessage res = tStoreBatchDetailServiceRemote.getBatchDetailByPri(req);
		logger.info("【根据主键查询批次详情信息】出参" + res);
		return res;
	}
	
	/**
	 * 保存批次详情信息
	 * @param req
	 * @return
	 * @throws Exception 
	 */
	public static ResMessage saveBatchDetail(ReqMessage req) throws Exception{
		logger.info("【保存批次详情信息】开始");
		logger.info("【保存批次详情信息】入参" + req);
		ResMessage res = tStoreBatchDetailServiceRemote.insertBatchDetail(req);
		logger.info("【保存批次详情信息】出参" + res);
		return res;
	}
	
	/**
	 * 更新批次详情信息
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public static ResMessage updateBatchDetail(ReqMessage req) throws Exception{
		logger.info("【更新批次详情信息】开始");
		logger.info("【更新批次详情信息】入参" + req);
		ResMessage res = tStoreBatchDetailServiceRemote.updateBatchDetailByPri(req);
		logger.info("【更新批次详情信息】出参" + res);
		return res;
	}
	
	/**
	 * 创建店铺信息
	 * @param req
	 * @return
	 * @throws IOException 
	 * @throws IllegalArgumentException 
	 */
	public static ResMessage createStore(ReqMessage req) throws Exception{
		logger.info("【创建店铺信息】开始");
		ResMessage res = new ResMessage();
	/**
	 * merId不为空，说明已经开通过主商户
	 */
		if (StringUtils.isNotBlank((String)req.get("merId"))) {
			//~~~~~~~~~~~~~~~~~验证店铺简称是否重名~~~~~~~~~~~~~~~~~
			Map<String, String> map = ValidateUtil.storeShortSame((String)req.get("storeShortName"), (String)req.get("merId"));	
			if (!map.get("retCode").equals("0000")) {
				res.put("retCode","0001");
				res.put("retMsg",map.get("retMsg"));
				return res;
			}
			//~~~~~~~~~~~~~~~~~如果用户开小微店铺，则需要判断一下用户有没有开通提前结算产品、有没有开通基金产品~~~~~~~~~~~~~~~~~
			if (req.get("storeType").equals("0")) {
				ReqMessage reqChanne = ReqMessageUtil.makeOpReq();
				reqChanne.put("storeId",req.get("merId"));//应用编号 60000680
				//reqChanne.put("productId",PRODUCTID_ADVANCESETTLE);//模板编号
				logger.info("【根据主键查询渠道表接口】入参：" + reqChanne);
				ResMessage resChanne =appChannelServiceRemote.queryListAppChannel(reqChanne);
				logger.info("【根据主键查询渠道表接口】出参：" + resChanne);
				if ("0000".equals(resChanne.getRetCode())) {	//返回成功，说明已经开通了提前结算产品
					List<AppChannel> appChannels = (List<AppChannel>) resChanne.getValue("resultList");
					for (AppChannel appChannel : appChannels) {
						if (PRODUCTID_ADVANCESETTLE.equals(appChannel.getProductId())) {
							res.put("retCode", "0001");
							res.put("retMsg", "您已开通了提前结算产品，暂不支持同时开通小微店铺");
							logger.error("【根据主键查询渠道表】成功，说明：已开通了提前结算产品，暂不支持同时开通小微店铺");
							return res;
						}
					}
				}
//				Map<String, Object> reqFund = new HashMap<String, Object>();
//				reqFund.put("rpid", reqChanne.getRpid());//流水号
//				reqFund.put("reqDate", reqChanne.getReqDate());//日期
//				reqFund.put("reqTime", reqChanne.getReqTime());//时间
//				reqFund.put("fundNo",SAAS_FUNDNO);
//				reqFund.put("fundMerId",SAAS_FUNDMERID);
//				reqFund.put("userMerId",req.get("merId"));
//				reqFund.put("merUserId",req.get("merId"));
//				reqFund.put("bProductId",B_PRODUCT_ID);
//				logger.info("【基金企业/个人开户信息查询】入参" + reqFund + "【请求地址】"+ FUND_OPEN_ACCSEARCH);	
//				Map<String, Object> resFund = HttpUtil.httpPostXStream2XStream(FUND_OPEN_ACCSEARCH, reqFund);
//				logger.info("【基金企业/个人开户信息查询】返回参数：" + resFund);
				
				//不知道为什么，不能用HttpUtil.httpPostXStream2XStream，所以只能用下面的方法了
				ReqMessage reqFund = ReqMessageUtil.makeOpReq();
				reqFund.put("merId",req.get("merId")); //主商户号 68000044
				logger.info("【基金企业/个人开户信息查询】入参" + reqFund);	
				ResMessage resFund = fundServiceRemote.queryFundMerInfo(reqFund);
				logger.info("【基金企业/个人开户信息查询】返回参数：" + resFund);
				if ("0000".equals(resFund.getRetCode())) {
					res.put("retCode", "0001");
					res.put("retMsg", "您已开通了基金产品，暂不支持同时开通小微店铺");
					logger.info("【查询商户是否开通基金产品】成功，说明：已开通了基金产品，暂不支持同时开通小微店铺");
					return res;
				}
			}
			//~~~~~~~~~~~~~~~~~生成店铺编号~~~~~~~~~~~~~~~~~
			String storeId = createNewStoreId();
			if (StringUtils.isEmpty(storeId)) {
				res.put("retCode", "0001");
				res.put("retMsg", "服务器异常，请稍后再试");
				return res;
			}
			//~~~~~~~~~~~~~~~~~创建子商户~~~~~~~~~~~~~~~~~
			ReqMessage reqStore = ReqMessageUtil.makeOpReq();
			reqStore.put("storeId",storeId);//店铺编号
			reqStore.put("merId",req.get("merId"));//主商户号
			reqStore.put("agentId",req.get("agentId"));//代理商编号
			reqStore.put("salesmanId",req.get("salesmanId"));//业务员
			reqStore.put("payeeName",req.get("payeeName"));//收款人
			reqStore.put("payeeInidcard",req.get("payeeInidcard"));//收款人身份证号（加密）
			reqStore.put("payeeInidcardValid",req.get("payeeInidcardValid"));//有效期
			reqStore.put("payeeMobileId",req.get("payeeMobileId"));//收款人手机
			reqStore.put("merId",req.get("merId"));//主商户号
			reqStore.put("defultStore",req.get("defultStore"));//默认店铺
			reqStore.put("registerProcsState",req.get("registerProcsState"));//状态
			reqStore.put("storeShortName",req.get("storeShortName"));//简称
			reqStore.put("storeCategory",((String)req.get("storeCategory")).replaceAll("/", "&"));//商户类别
			reqStore.put("phone",req.get("phone"));//客服电话
			reqStore.put("storeAddrProv",req.get("storeAddrProv"));//省
			reqStore.put("storeAddrCity",req.get("storeAddrCity"));//市
			reqStore.put("storeAddrArea",req.get("storeAddrArea"));//区/县
			reqStore.put("storeFullAddr",req.get("storeFullAddr"));//详细地址
			reqStore.put("storeType",req.get("storeType"));//商户类型：0小微；1个体（企业）
			reqStore.put("storeGrade","B");//商户评级：A有营业执照；B无营业执照
			reqStore.put("prestorePhone",req.get("prestorePhone"));//银行预留手机号
			reqStore.put("type","1");//批量导入标识：0单个；1批量
			reqStore.put("isDel","0");//默认不删除：0未删除；1已删除
			reqStore.put("labelOne",req.get("labelOne"));//标签一
			reqStore.put("labelTwo",req.get("labelTwo"));//标签二
			reqStore.put("email",req.get("email"));//邮箱
			if (req.get("storeType").equals("1")) {
				reqStore.put("storeGrade","A");
				reqStore.put("licenseNo",req.get("licenseNo"));//营业执照
				reqStore.put("storeFullName",req.get("storeFullName"));//商户全称
				reqStore.put("registerDate",req.get("registerDate"));//注册日期
				reqStore.put("mainBusiness",req.get("mainBusiness"));//主营业务
				reqStore.put("rgstaddress",req.get("rgstaddress"));//注册地址
				reqStore.put("categoryManName",req.get("categoryManName"));//经营者姓名
				reqStore.put("categoryManCardno",req.get("categoryManCardno"));//身份证号码(加密)
				reqStore.put("categoryInidcardValid",req.get("categoryInidcardValid"));//证件有效期
			}
			res = saveStoreInf(reqStore);
			res.put("storeId", storeId);
			res.put("merId", req.get("merId"));
			res.put("retCode", "0000");
		}else {
	/**
	 * merId为空，说明未开通过主商户，需要先开主商户，再开子商户
	 */
			//~~~~~~~~~~~~~~~~~生成店铺编号（主商户号）~~~~~~~~~~~~~~~~~
			String merId = createNewStoreId();
			if (StringUtils.isEmpty(merId)) {
				res.put("retCode", "0001");
				res.put("retMsg", "服务器异常，请稍后再试");
				return res;
			}
			//~~~~~~~~~~~~~~~~~创建主商户~~~~~~~~~~~~~~~~~
			ReqMessage reqStore = ReqMessageUtil.makeOpReq();
			reqStore.put("storeId",merId);//店铺编号
			reqStore.put("agentId",req.get("agentId"));//代理商编号
			reqStore.put("salesmanId",req.get("salesmanId"));//业务员
			reqStore.put("payeeName",req.get("payeeName"));//收款人
			reqStore.put("payeeInidcard",req.get("payeeInidcard"));//收款人身份证号（加密）
			reqStore.put("payeeInidcardValid",req.get("payeeInidcardValid"));//有效期
			reqStore.put("payeeMobileId",req.get("payeeMobileId"));//收款人手机
			reqStore.put("isDel","0");//默认不删除：0未删除；1已删除
			res = saveStoreInf(reqStore);
			if (res.getRetCode().equals("0000")) {
				//~~~~~~~~~~~~~~~~~生成店铺编号~~~~~~~~~~~~~~~~~
				String storeId = createNewStoreId();
				if (StringUtils.isEmpty(storeId)) {
					res.put("retCode", "0001");
					res.put("retMsg", "服务器异常，请稍后再试");
					return res;
				}
				//~~~~~~~~~~~~~~~~~创建子商户~~~~~~~~~~~~~~~~~
				reqStore.put("storeId",storeId);//店铺编号
				reqStore.put("merId",merId);//主商户号
				reqStore.put("defultStore",req.get("defultStore"));//默认店铺
				reqStore.put("registerProcsState",req.get("registerProcsState"));//状态
				reqStore.put("storeShortName",req.get("storeShortName"));//简称
				reqStore.put("storeCategory",((String)req.get("storeCategory")).replaceAll("/", "&"));//商户类别
				reqStore.put("phone",req.get("phone"));//客服电话
				reqStore.put("storeAddrProv",req.get("storeAddrProv"));//省
				reqStore.put("storeAddrCity",req.get("storeAddrCity"));//市
				reqStore.put("storeAddrArea",req.get("storeAddrArea"));//区/县
				reqStore.put("storeFullAddr",req.get("storeFullAddr"));//详细地址
				reqStore.put("storeType",req.get("storeType"));//商户类型：0小微；1个体（企业）
				reqStore.put("storeGrade","B");//商户评级：A有营业执照；B无营业执照
				reqStore.put("prestorePhone",req.get("prestorePhone"));//银行预留手机号
				reqStore.put("type","1");//批量导入标识：0单个；1批量
				reqStore.put("isDel","0");//默认不删除：0未删除；1已删除
				reqStore.put("labelOne",req.get("labelOne"));//标签一
				reqStore.put("labelTwo",req.get("labelTwo"));//标签二
				reqStore.put("email",req.get("email"));//邮箱
				if (req.get("storeType").equals("1")) {
					reqStore.put("storeGrade","A");
					reqStore.put("licenseNo",req.get("licenseNo"));//营业执照号
					reqStore.put("storeFullName",req.get("storeFullName"));//商户全称
					reqStore.put("registerDate",req.get("registerDate"));//注册日期
					reqStore.put("mainBusiness",req.get("mainBusiness"));//主营业务
					reqStore.put("rgstaddress",req.get("rgstaddress"));//注册地址
					reqStore.put("categoryManName",req.get("categoryManName"));//经营者姓名
					reqStore.put("categoryManCardno",req.get("categoryManCardno"));//身份证号码(加密)
					reqStore.put("categoryInidcardValid",req.get("categoryInidcardValid"));//证件有效期
				}
				res = saveStoreInf(reqStore);
				res.put("storeId", storeId);
				res.put("merId", merId);
				res.put("retCode", "0000");
			}
		}
		return res;
	}
	
	/**
	 * 生成商户号，主商户号与子商户号自增
	 * @return
	 */
	public static  String createNewStoreId() throws Exception{
		ReqMessage req = ReqMessageUtil.makeOpReq();
		ResMessage res = null;
		for (int i = 69; i > 61; i--) {
			req.put("meridHeade", i + "");
				logger.info("【获取最大的商户编号】入参" + req);
				res = storeInfServiceRemote.getMaxMainMerIdByMeridHeade(req);
				logger.info("【获取最大的商户编号】出参" + res);
			if (!"0000".equals(res.getRetCode())) {
				logger.info("【获取最大的商户编号】失败" );
				return null;
			}
			String maxMainMerId = (String) res.getResMap().get("maxMainMerId");
			if (StringUtils.isNotEmpty(maxMainMerId)) {
				if (maxMainMerId.equals(i + "999999")) {
					continue;
				}else {
					return Integer.valueOf(maxMainMerId) + 1 + "";
				}
			}else {
				return i + "000000";
			}
		}
		return null;
	}
	
	/**
	 * 创建店铺（主、子）
	 * @param req
	 * @return
	 */
	public static ResMessage saveStoreInf(ReqMessage req) throws Exception{
		logger.info("【创建店铺】入参" + req);
		ResMessage res = storeInfServiceRemote.saveStoreInf(req);
		logger.info("【创建店铺】出参" + res);
		return res;
	}
}
